<template>
  <div class="courier-list-container">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-bar">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索配送员姓名、手机号或工号"
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-select v-model="filterStatus" placeholder="工作状态" clearable @change="handleSearch" class="filter-item">
          <el-option label="在职" value="active" />
          <el-option label="停职" value="suspended" />
          <el-option label="离职" value="inactive" />
        </el-select>
        
        <el-select v-model="filterArea" placeholder="配送区域" clearable @change="handleSearch" class="filter-item">
          <el-option v-for="area in areaOptions" :key="area" :label="area" :value="area" />
        </el-select>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="action-section">
        <el-button type="primary" @click="$emit('add-courier')" class="action-button">
          <el-icon><Plus /></el-icon>新增配送员
        </el-button>
        <el-button type="success" @click="refreshData" class="action-button">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 列表区域 -->
    <div class="table-container">
      <el-table
        :data="filteredCouriers"
        style="width: 100%"
        @row-click="handleRowClick"
        v-loading="loading"
        border
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" width="60" align="center" />
        <el-table-column prop="jobNumber" label="工号" min-width="140" align="center" />
        <el-table-column prop="name" label="姓名" min-width="100" align="center" />
        <el-table-column prop="phone" label="手机号" min-width="130" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="area" label="配送区域" min-width="120" />
        <el-table-column prop="status" label="状态" min-width="90" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryCount" label="累计派送量" min-width="120" align="center" sortable />
        <el-table-column prop="entryDate" label="入职日期" min-width="120" align="center" sortable />
        <el-table-column prop="createDate" label="创建时间" min-width="160" align="center" sortable>
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" @click.stop="$emit('edit-courier', scope.row)" size="small">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button link type="primary" @click.stop="$emit('view-courier', scope.row)" size="small">
                <el-icon><View /></el-icon>详情
              </el-button>
                          <el-popconfirm
              title="确定要删除此配送员吗？删除后将同时删除关联的用户账户！"
              @confirm="handleDelete(scope.row)"
              confirm-button-text="确定删除"
              cancel-button-text="取消"
              confirm-button-type="danger"
            >
              <template #reference>
                <el-button 
                  link 
                  type="danger" 
                  size="small"
                  @click.stop
                >
                  <el-icon><Delete /></el-icon>删除
                </el-button>
              </template>
            </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!filteredCouriers.length && !loading" description="暂无配送员数据" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Refresh, Edit, View, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getCouriers, deleteCourier, type Courier } from '@/api/courier'

// 页面状态
const loading = ref(false)
const searchQuery = ref('')
const filterStatus = ref('')
const filterArea = ref('')
const couriers = ref<Courier[]>([])

// 区域选项 - 从实际数据中动态获取
const areaOptions = computed(() => {
  const areas = new Set(couriers.value.map(courier => courier.area))
  return Array.from(areas).filter(Boolean)
})

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    active: '在职',
    suspended: '停职',
    inactive: '离职'
  }
  return statusMap[status as keyof typeof statusMap] || status
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const typeMap = {
    active: 'success',
    suspended: 'warning',
    inactive: 'info'
  }
  return typeMap[status as keyof typeof typeMap] || ''
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 筛选后的配送员列表
const filteredCouriers = computed(() => {
  return couriers.value.filter(courier => {
    const matchesSearch = searchQuery.value ? 
      courier.name.includes(searchQuery.value) || 
      courier.phone.includes(searchQuery.value) || 
      courier.jobNumber.includes(searchQuery.value) : true
    
    const matchesStatus = filterStatus.value ? courier.status === filterStatus.value : true
    const matchesArea = filterArea.value ? courier.area === filterArea.value : true
    
    return matchesSearch && matchesStatus && matchesArea
  })
})

// 点击行事件
const handleRowClick = (row: Courier) => {
  emit('view-courier', row)
}

// 删除配送员
const handleDelete = async (row: Courier) => {
  if (!row.id) return
  
  loading.value = true
  try {
    const response = await deleteCourier(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await loadData() // 重新加载数据
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    console.error('删除配送员失败:', error)
    ElMessage.error(error.message || '删除失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 前端筛选，实际可以改为后端搜索
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const response = await getCouriers()
    if (response.code === 200) {
      couriers.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载数据失败')
    }
  } catch (error: any) {
    console.error('加载配送员数据失败:', error)
    ElMessage.error(error.message || '加载数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 定义组件事件
const emit = defineEmits<{
  'add-courier': []
  'edit-courier': [courier: Courier]
  'view-courier': [courier: Courier]
}>()

// 初始化时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.courier-list-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 搜索和筛选区域样式 */
.search-filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 24px;
  align-items: center;
}

.search-section {
  flex: 1;
  min-width: 280px;
}

.search-input {
  width: 100%;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-item {
  width: 140px;
}

.action-section {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.action-button {
  display: flex;
  align-items: center;
}

.action-button .el-icon {
  margin-right: 6px;
}

/* 表格区域样式 */
.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.action-buttons {
  display: flex;
  justify-content: center;
  flex-wrap: nowrap;
  gap: 4px;
}

@media (max-width: 768px) {
  .search-filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section,
  .filter-section,
  .action-section {
    width: 100%;
  }
  
  .action-section {
    margin-left: 0;
    justify-content: flex-end;
  }
}
</style> 